# -*- coding: utf-8 -*-

from django.http import HttpResponse
from wjapp.models import WjInfo, WjUser, WjBlock
from django.db.models import Q
from django.views.decorators.csrf import csrf_exempt
from django.utils import timezone as datetime
from cStringIO import StringIO
from collections import defaultdict
import requests
import json
import base64
import csv

WJ_FAKE = False


@csrf_exempt
def wj_xxx_csv(request):
    # 给wj用的
    wid = request.GET.get('wid')
    if wid:
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = 'attachment; filename="result.csv"'
        writer = csv.writer(response)

        info = WjInfo.objects.get(id=int(wid))
        questions = json.loads(info.question_json)
        users = defaultdict(lambda: defaultdict(str))  # {'open_id': {1: '', 2: ''}
        headers = ['序号']
        for idx, question in enumerate(questions):
            title = question.get('title', '-')
            headers.append(title)
            question_type = question['questionType']
            fill_actors = question['fillActors']
            answers = question['answers']
            if question_type == '1':
                for answer in answers:
                    actors = answer['actors']
                    for actor in actors:
                        users[actor][idx] = users[actor][idx] + ';' + answer['value']
            else:
                for actor in fill_actors:
                    users[actor['openId']][idx] = actor['value']

        writer.writerow(headers)
        idx = 0
        for open_id, vs in users.iteritems():
            idx += 1
            rw = []
            for i in range(len(headers) - 1):
                rw.append(vs[i])
            writer.writerow([str(idx)] + rw)
        return response
    else:
        return HttpResponse(json.dumps({'code': -1}))


@csrf_exempt
def wj_xxx(request):
    # 给wj用的
    body = json.loads(request.body)
    cmd = body['data']['cmd']
    try:
        open_id = body['data']['userInfo']['openId']
        if open_id and WjBlock.objects.filter(open_id=open_id).exists():
            return HttpResponse(json.dumps({'code': -1, 'openId': open_id, 'notice': ''}))
    except:
        open_id = ''

    if cmd == 'upload':
        value = body['data']['value']
        io_file = StringIO(base64.decodestring(value))
        # 自己注册图床的账号在sm.ms上面
        r = requests.post(url="https://sm.ms/api/v2/upload", data=None, files={'smfile': io_file}, headers={'Authorization': 'BpuRh2cijbbblIcG8lfiN94vaaaaaaaa'})
        j = r.json()
        try:
            url = j['data']['url']
        except:
            try:
                url = j['images']
            except:
                url = ''
        #
        return HttpResponse(json.dumps({'url': url}))

    if cmd == 'submitWj':
        open_id = body['data']['userInfo']['openId']
        value = body['data']['value']
        title = value['title'] or ''
        bref = value['bref'] or ''
        cover = value['cover']
        open_type = int(value.get('openType', '1'))
        if open_type == 1:
            is_open = True
        else:
            is_open = False
        wj_pass = value.get('wjPass', '')[:100]
        questions = value['questions']
        question_json = json.dumps(questions)
        now = datetime.datetime.now()

        wj_info = WjInfo.objects.create(
            open_id=open_id,
            title=title,
            bref=bref,
            cover=cover,
            is_open=is_open,
            wj_pass=wj_pass,
            question_json=question_json,
            create_date=now,
            update_date=now,
            expire_date=now + datetime.timedelta(days=2000),
            enabled=True
        )

        return HttpResponse(json.dumps({'code': 0, 'wid': wj_info.id, 'openId': open_id}))

    if cmd == 'indexWjs':
        open_id = body['data']['userInfo']['openId']
        kw = body['data'].get('kw', '')
        cmd2 = body['data'].get('cmd2', '')
        user = body['data'].get('user', '')
        if WJ_FAKE and 'kw' in body['data']:
            return HttpResponse(json.dumps({'code': 0, 'indexWjs': [], 'openId': open_id, 'enableCreate': False,
                                            'dm1': '联系客服',
                                            'dm2': '联系客服',
                                            'dm3': '搜索答题',
                                            'dm4': '公开答题',
                                            'dm5': '公开答题',
                                            'dm6': '公开答题',
                                            'dm7': '公开答题',
                                            'dm8': '公开答题',
                                            'dm9': '公开答题',
                                            'dm10': '公开答题',
                                            'dm11': '我的答题',
                                            }))

        index_wjs = []
        if cmd2 and user:
            if cmd2 == 'create':
                wj_infos = WjInfo.objects.filter(open_id=user, enabled=True).order_by('-id')[:100]
            elif cmd2 == 'part':
                wj_infos = WjInfo.objects.filter(part_wj_json__contains=user, enabled=True).order_by('-id')[:100]
            else:
                raise Exception('')
        else:
            if 'kw' in body['data']:
                wj_infos = WjInfo.objects.filter(Q(title__icontains=kw) | Q(bref__icontains=kw) | Q(internal_search__icontains=kw), enabled=True, is_open=True). \
                               order_by('-part_wj_count')[:50]
            else:
                wj_infos = WjInfo.objects.filter(enabled=True, is_open=True).order_by('-part_wj_count')[:8]

        if cmd2 == 'home':
            wj_infos = WjInfo.objects.filter(is_home=True, enabled=True, is_open=True).order_by('-part_wj_count')[:8]

        for wj_info in wj_infos:
            title_fix = wj_info.title
            if len(title_fix) > 20:
                title_fix = title_fix[:17] + '...'

            #
            questions = json.loads(wj_info.question_json)
            for idx, question in enumerate(questions):
                question['idx'] = idx

                self_fill_actor = {}
                for fill_actor in question['fillActors']:
                    if fill_actor['openId'] == open_id:
                        self_fill_actor = fill_actor
                if self_fill_actor:
                    question['fillActors'] = [self_fill_actor]
                    question['fillText'] = self_fill_actor['value']
                else:
                    question['fillActors'] = []
                    question['fillText'] = ''
                    question['fillTexts'] = [fa['value'] for fa in question['fillActors']][:100]

                for answer in question['answers']:
                    actors = answer['actors']
                    answer['actorCount'] = len(actors)
                    if open_id in actors:
                        actors = [open_id]
                        answer['selfChoice'] = True
                    else:
                        actors = []
                        answer['selfChoice'] = False
                    answer['actors'] = actors

            #
            if wj_info.id in [3, 4, 5, 6, 579, 585]:
                cover = '/images/c/wj_%s.jpg' % wj_info.id
            else:
                cover = wj_info.cover or ''
            index_wjs.append({
                'id': wj_info.id,
                'title': wj_info.title,
                'titleFix': title_fix,
                'bref': wj_info.bref,
                'cover': cover,
                'isOpen': wj_info.is_open,
                'wjPass': wj_info.wj_pass,
                'questions': questions,
                'partWjCount': wj_info.part_wj_count,
                'isSelfPart': True if open_id in wj_info.part_wj_json else False,
                'creator': wj_info.open_id,
                'isSelfCreate': wj_info.open_id == open_id,
            })

        """
        'dm1': '联系客服',
        'dm2': '联系客服',
        'dm3': '搜索答题',
        'dm4': '公开答题',
        'dm5': '公开答题',
        'dm6': '公开答题',
        'dm7': '公开答题',
        'dm8': '公开答题',
        'dm9': '公开答题',
        'dm10': '公开答题',
        'dm11': '我的答题',
       
        'dm1': '创建问卷',
        'dm2': '联系客服创建问卷',
        'dm3': '搜索问卷',
        'dm4': '公开问卷',
        'dm5': '公开问卷',
        'dm6': '问卷调查',
        'dm7': '创建问卷',
        'dm8': '添加题目',
        'dm9': '查看问卷',
        'dm10': '我的问卷',
        'dm11': '我的问卷',
        """
        if not WJ_FAKE:
            return HttpResponse(json.dumps({'code': 0, 'indexWjs': index_wjs, 'openId': open_id, 'enableCreate': True,
                                            'dm1': '创建问卷',
                                            'dm2': '联系客服创建问卷',
                                            'dm3': '搜索问卷',
                                            'dm4': '官方示例',
                                            'dm5': '公开问卷',
                                            'dm6': '问卷调查',
                                            'dm7': '创建问卷',
                                            'dm8': '添加题目',
                                            'dm9': '查看问卷',
                                            'dm10': '我的问卷',
                                            'dm11': '我的问卷',
                                            }))
        return HttpResponse(json.dumps({'code': 0, 'indexWjs': index_wjs, 'openId': open_id, 'enableCreate': False,
                                        'dm1': '联系客服',
                                        'dm2': '联系客服',
                                        'dm3': '搜索答题',
                                        'dm4': '公开答题',
                                        'dm5': '公开答题',
                                        'dm6': '公开答题',
                                        'dm7': '公开答题',
                                        'dm8': '公开答题',
                                        'dm9': '公开答题',
                                        'dm10': '公开答题',
                                        'dm11': '我的答题',
                                        }))

    if cmd == 'getDetail':
        open_id = body['data']['userInfo']['openId']
        wid = body['data']['wid']
        info = WjInfo.objects.get(id=int(wid))
        questions = json.loads(info.question_json)
        has_fill = False
        #
        for idx, question in enumerate(questions):
            question['idx'] = idx
            if int(question['questionType']) == 2:
                has_fill = True

            temp_fill_actors = [fa for fa in question['fillActors']]
            self_fill_actor = {}
            for fill_actor in question['fillActors']:
                if fill_actor['openId'] == open_id:
                    self_fill_actor = fill_actor
            if self_fill_actor:
                question['fillActors'] = [self_fill_actor]
                question['fillText'] = self_fill_actor['value']
            else:
                question['fillActors'] = []
                question['fillText'] = ''
            if open_id == info.open_id:
                question['fillTexts'] = [fa['value'].strip() for fa in temp_fill_actors if fa['value'] and fa['value'].strip()]
            else:
                question['fillTexts'] = [fa['value'] + u'（简答题只有创建者才能查看全部）' for fa in question['fillActors']]

            for answer in question['answers']:
                actors = answer['actors']
                answer['actorCount'] = len(actors)
                if open_id in actors:
                    actors = [open_id]
                    answer['selfChoice'] = True
                else:
                    actors = []
                    answer['selfChoice'] = False
                answer['actors'] = actors

        #
        wj_info = {
            'id': info.id,
            'title': info.title,
            'bref': info.bref,
            'cover': info.cover,
            'isOpen': info.is_open,
            'wjPass': info.wj_pass,
            'questions': questions,
            'partWjCount': info.part_wj_count,
            'isSelfPart': True if open_id in info.part_wj_json else False,
            'isSelfCreate': info.open_id == open_id,
            'creator': info.open_id,
            'hasFill': has_fill
        }
        return HttpResponse(json.dumps({'code': 0, 'wjInfo': wj_info, 'openId': open_id}))

    if cmd == 'submitVote':
        if WJ_FAKE:
            return HttpResponse(json.dumps({'code': 0}))
        open_id = body['data']['userInfo']['openId']
        wid = body['data']['wid']
        results = body['data']['results']
        wj_info = WjInfo.objects.get(id=int(wid))
        questions = json.loads(wj_info.question_json)

        for result in results:
            qi = int(result['qi'])
            if result['questionType'] == '1':
                for ai in result['as']:
                    ai = int(ai)
                    if open_id not in questions[qi]['answers'][ai]['actors']:
                        questions[qi]['answers'][ai]['actors'].append(open_id)
            else:
                if open_id not in [fa['openId'] for fa in questions[qi]['fillActors']]:
                    questions[qi]['fillActors'].append({'openId': open_id, 'value': result['fillValue']})
        part_wj_json = wj_info.part_wj_json or json.dumps([])
        part_wj_users = json.loads(part_wj_json)
        part_wj_users.append(open_id)
        part_wj_users = list(set(part_wj_users))

        wj_info.question_json = json.dumps(questions)
        wj_info.part_wj_json = json.dumps(part_wj_users)
        wj_info.part_wj_count = len(part_wj_users)
        wj_info.save()
        return HttpResponse(json.dumps({'code': 0}))

    if cmd == 'mineLogin':
        open_id = body['data']['userInfo']['openId']
        user_info = body['data']['ui']
        nickname = user_info['nickName']
        avatar = user_info['avatarUrl']
        try:
            WjUser.objects.create(
                open_id=open_id,
                nickname=nickname,
                avatar=avatar,
                create_date=datetime.datetime.now(),
                enabled=True
            )
        except:
            pass
        return HttpResponse(json.dumps({'code': 0}))

    return HttpResponse(json.dumps({}))
